/****************************************
 * Copyright (c) 2015 NiuWa.
 * All rights reserved.
 * Created on 2015年3月31日
 * 
 * Contributors:
 * 	   zhangmingtao - initial implementation
 ****************************************/
package com.niuwa.p2p.service.impl.message;

import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

/**
 * @title 消息推送APi
 *
 * @author zhangmingtao
 * @version 1.0
 * @created 2015年3月31日
 */
@Service("newMessageApi")
public class MessageApiImpl implements MessageApi {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	/* 消息推送一次最多推送个数 */
	private static final int MAX_LENGTH = 1000;

	/**
	 * 通过别名推送消息，批量操作
	 * 
	 */
	@Override
	public void pushMessageBatch(Set<String> set, String title, String message, String msgType, String memo) {
		MessagePush messagePush = new MessagePush(title, message, msgType, memo);
		logicSendPush(set, messagePush);
	}
	
	/**
	 * 根据别名推送消息，单个
	 */
	@Override
	public void pushMessage(String receiver, String title, String message, String msgType, String memo) {
		MessagePush messagePush = new MessagePush(title, message, msgType, memo);
		if (!Strings.isNullOrEmpty(receiver)) {
			sendPush(messagePush, Sets.newHashSet(receiver));
		}
	}

	/**
	 * 处理批量推送消息，单次最多1000
	 * 
	 * @param set
	 * @param messagePush
	 */
	private void logicSendPush(Set<String> set, MessagePush messagePush) {
		try {
			if (!CollectionUtils.isEmpty(set)) {
				java.util.List<java.util.List<String>> partition = Lists.partition(Lists.newArrayList(set), MAX_LENGTH);
				for (java.util.List<String> list : partition) {
					sendPush(messagePush, Sets.newHashSet(list));
				}
			}
		} catch (Exception e) {
			logger.error(this.getClass().getSimpleName() + "推送消息error: case[" + e.getMessage() + "]");
		}
	}

	/**
	 * 调用第三方推送
	 * 
	 * @param messagePush
	 * @param set
	 */
	private void sendPush(MessagePush messagePush, Set<String> set) {
		try {
			messagePush.sendPushAliasMessage(set);
		} catch (Exception e) {
			logger.error(this.getClass().getSimpleName() + "推送自定义消息error: case[" + e.getMessage() + "]");
		}
		try {
			messagePush.sendPushAliasNotification(set);
		} catch (Exception e) {
			logger.error(this.getClass().getSimpleName() + "推送通知error: case[" + e.getMessage() + "]");
		}
	}
}
